﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.SqlClient;
using System.Configuration;

namespace Rizmar
{
    public partial class TaxasForm : Form
    {
        public TaxasForm()
        {
            InitializeComponent();
        }

        private void buttonCancelar_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (pisTextBox.TextLength > 0 && irpjTextBox.TextLength > 0 && ioftextBox.TextLength > 0 && issTextBox.TextLength > 0)
            {
                SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                cn.Open();
                string cmdStr =
                    @"UPDATE Taxa 
                        SET 
                            pis_cofins = " + pisTextBox.Text.Replace(',','.') + @" ,
                            irpj = " + irpjTextBox.Text.Replace(',', '.') + @" ,
                            iof = " + ioftextBox.Text.Replace(',', '.') + @" ,
                            iss = " + issTextBox.Text.Replace(',', '.') + "";
                bool sucesso = true;
                using (SqlCommand cmd = new SqlCommand(cmdStr, cn))
                {
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException)
                    {
                        MessageBox.Show("Dados inválidos", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        sucesso = false;
                    }
                }
                cn.Close();
                if (sucesso)
                {
                    MessageBox.Show("Taxas atualizadas com sucesso", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
            }
            else MessageBox.Show("Campos inválidos!", "Erro");
        }

        private void TaxasForm_Load(object sender, EventArgs e)
        {
            /* TODO: Carregar os valores do DB para os textboxes */
            SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            cn.Open();

            using (SqlCommand cmd = new SqlCommand("SELECT * FROM [Taxa]", cn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                /* Primeiro verifica se as taxas já estão setadas */
                bool novo = true;
                if (dr.HasRows) novo = false;
                dr.Close();

                /* Se não estiverem setadas, inicializar valores com zero */
                if (novo)
                {
                    using (SqlCommand insert_cmd = new SqlCommand("INSERT INTO [Taxa] VALUES (0, 0, 0, 0)", cn))
                    {
                        insert_cmd.ExecuteNonQuery();
                    }
                }

                /* Agora, carregar valores do DB para textboxes */
                dr = cmd.ExecuteReader();
                dr.Read();

                /* Formatação para quatro casas decimais */
                pisTextBox.Text = string.Format("{0:0.0000}", dr.GetFloat(0));
                irpjTextBox.Text = string.Format("{0:0.0000}", dr.GetFloat(1));
                ioftextBox.Text = string.Format("{0:0.0000}", dr.GetFloat(2));
                issTextBox.Text = string.Format("{0:0.0000}", dr.GetFloat(3));

                dr.Close();
            }
        }

        public float getPisTextBox()
        {
            return float.Parse(pisTextBox.Text);
        }
        public float getIrpjTextBox()
        {
            return float.Parse(irpjTextBox.Text);
        }
        public float getIofTextBox()
        {
            return float.Parse(ioftextBox.Text);
        }
        public float getIssTextBox()
        {
            return float.Parse(issTextBox.Text);
        }
    }
}
